/*
 * @Author: your name
 * @Date: 2022-03-17 19:36:28
 * @LastEditTime: 2022-05-02 09:44:17
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \blog-system-front\src\Pages\Article\writeArticle\saveForm.js
 */
import { Form, Input, Tag, Upload } from "antd";
import React, { useEffect, useState } from "react";
import CategoryTabSelect from "../../../components/CategoryTreeSelect/CategoryTabSelect";
import request from "@/api";
import { PlusOutlined } from "@ant-design/icons";
import "./index.less";

export default function SaveForm(props) {
  const [category, setCategory] = useState([]);
  const { form, setCategortInfo } = props;
  const [coverUrl, setCoverUrl] = useState(form.getFieldValue().articleCover);
  const [labelVisiable, setLabelVisiable] = useState(false);
  const [tags, setTags] = useState([]);
  /**
   * @description: 初始化标签
   * @param {*} params
   * @return {*}
   */
  const initData = (params) => {
    request({
      url: "v1/article/category",
      method: "GET",
      params,
    }).then((res) => {
      const { content } = res;
      setCategory(content);
      const categoryIdArr = form.getFieldValue().categoryId.split(",");
      const tags = [];
      categoryIdArr.forEach((d) => {
        const data = content.filter((item) => item.category_id === Number(d));
        tags.push(data[0]);
      });
      setTags(tags);
    });
  };
  useEffect(() => {
    initData();
  }, []);
  useEffect(() => {
    setCategortInfo(tags);
  }, [tags]);

  /**
   * @description: 文章封面图上传处理
   * @param {*} file
   * @return {*}
   */
  const handleFileChange = (file) => {
    const { response, status } = file.file;
    if (status === "done") {
      setCoverUrl(response.url);
      form.setFieldsValue({
        articleCover: response.url,
      });
    }
  };
  /**
   * @description: 标签多选赋值
   * @param {*} data
   * @param {*} node
   * @return {*}
   */
  const addTag = (data) => {
    const newTags = tags.concat();
    newTags.push(data);
    form.setFieldsValue({ category: newTags });
    setTags(newTags);
  };
  return (
    <Form form={form} autoComplete="off">
      <Form.Item
        name="articleName"
        label="文章名称"
        rules={[{ required: true, message: "请输入文章名称" }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name="category"
        label="文章标签"
        rules={[{ required: true, message: "请选择文章标签" }]}
      >
        {tags.map((d, index) => {
          return (
            <Tag
              color="#277fce0d"
              closable
              visible
              style={{width: "40px"}}
              onClose={() => {
                const index = tags.findIndex(
                  (item) => d.category_id === item.category_id
                );
                const tempArr = tags.concat();
                if (index !== -1) {
                  tempArr.splice(index, 1);
                  setTags(tempArr);
                }
              }}
            >
              {d.category_name}
            </Tag>
          );
        })}
        <Tag className="site-tag-plus" onClick={() => setLabelVisiable(true)}>
          <PlusOutlined /> 选择文章标签
        </Tag>
        <div
          className="selecetlabel"
          style={{ display: labelVisiable ? "block" : "none" }}
        >
          <CategoryTabSelect
            category={category}
            addTag={addTag}
            tags={tags}
            close={() => setLabelVisiable(false)}
          ></CategoryTabSelect>
        </div>
      </Form.Item>
      <Form.Item name="description" label="文章描述">
        <Input.TextArea />
      </Form.Item>
      <Form.Item name="articleCover" label="文章封面">
        <Upload
          name="file"
          listType="picture-card"
          className="avatar-uploader"
          showUploadList={false}
          action="http://106.15.45.34:5000/v1/file-upload"
          headers={{
            Authorization: `bearer ${localStorage.getItem("token")}`,
          }}
          onChange={handleFileChange}
        >
          {coverUrl ? (
            <img src={coverUrl} style={{ width: "100%" }} />
          ) : (
            <div>{<PlusOutlined />}</div>
          )}
        </Upload>
      </Form.Item>
    </Form>
  );
}
